package com.voja.mrvica2.remoteimage;

import java.net.MalformedURLException;

import com.voja.mrvica2.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class RemoteImageView extends RelativeLayout {

	Context      context;
	AttributeSet attrSet;
	TypedArray   attrs;
	
	String      url = "";
	ImageView   image;
	ProgressBar throbber;
	
	public Bitmap      bitmap;
	
	public RemoteImageView(Context c, AttributeSet a) {
		super(c, a);
		
		this.context = c;
		this.attrSet = a;
		this.attrs   = context.getTheme().obtainStyledAttributes(a, R.styleable.RemoteImageView, 0, 0);
		
		inflateLayout();
		applyAttrs();
	}
	
	public void inflateLayout() {
		LayoutInflater inf = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inf.inflate(R.layout.remote_image, this, true);
		
		image    = getImageView();
		throbber = getThrobberView();
	}
	
	public ImageView getImageView() {
	    return (ImageView)findViewById(R.id.remoteImageView);
	}
	
	public ProgressBar getThrobberView() {
	    return (ProgressBar)findViewById(R.id.remoteThrobber);
	}
	
	public void setImage(String url) {
		applyAttrs(url);
	}
	
	public void applyAttrs() {
		url = attrs.getString(R.styleable.RemoteImageView_url);
		applyAttrs(url);
	}
	
	public void applyAttrs(String url) {
		
		try {
			throbber.setVisibility(View.VISIBLE);
			image.setVisibility(View.GONE);
			
			if (url != null && url.length()>0) {
				new RemoteImage(image, url, new OnRemoteImageLoadded(this)).execute();
			}
		} catch (MalformedURLException e) {
			throbber.setVisibility(View.GONE);
			
			TextView error = new TextView(context);
			error.setText("Error: URL("+url+") \n" + e.getMessage());
			addView(error);
		} finally {
			attrs.recycle();
		}
	}

}
